<template>
  <el-dialog
    class="flow-dialog"
    title="用户"
    :model-value="visible"
    width="30%"
    destroy-on-close
    center
    modal
    :close-on-click-modal="false"
    :show-close="false"
  >
    <el-form
      ref="formRef"
      :model="userForm"
      :rules="rules"
      inline-message
      :status-icon="true"
      label-width="80"
    >
      <el-form-item label="所属部门" prop="deptId">
        <el-tree-select
          v-model="userForm.deptId"
          node-key="id"
          :props="{
            value: 'id',
            label: 'label',
            children: 'children',
          }"
          highlight-current
          check-strictly
          lazy
          :load="loadDeptTree"
        />
      </el-form-item>
      <el-form-item label="昵称" prop="nickName">
        <el-input
          v-model="userForm.nickName"
          placeholder="请输入昵称"
          max="10"
          clearable
        />
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="userForm.username"
          placeholder="请输入用户名"
          max="20"
          clearable
        />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="userForm.password"
          placeholder="请输入密码"
          show-password
          clearable
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button
          type="primary"
          :loading="loading"
          :icon="useRenderIcon('material-symbols:check')"
          @click="submit()"
        >
          保存
        </el-button>
        <el-button
          type="danger"
          :loading="loading"
          :icon="useRenderIcon('material-symbols:close')"
          @click="close()"
        >
          关闭
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { FormInstance } from "element-plus";
import { UserModel } from "@/api/model/userModel";
import { defineComponent, reactive, ref } from "vue";
import { message } from "@/utils/message";
import { addUser, checkUsername } from "@/api/user";
import { getDeptTree } from "@/api/dept";

const loading = ref(false);
const visible = ref(false);
const formRef = ref<FormInstance>();
const userForm = ref<UserModel>({});

const validCode = async (rule, value, callback) => {
  if (value == null || value === "") {
    callback(new Error("请输入用户名"));
  } else {
    if (!/[A-Za-z0-9]{6,20}/.test(value)) {
      callback(new Error("用户名只能使用英文和数字，且必须在6到20个字符之间"));
    } else {
      const usable = await checkUsername(value);
      if (!usable) {
        callback(new Error("用户名已被使用"));
      }
    }
  }
  callback();
};

const rules = reactive({
  deptId: [{ required: true, message: "请选择所属部门", trigger: "blur" }],
  nickName: [
    { required: true, message: "请输入昵称", trigger: "blur" },
    {
      min: 2,
      max: 10,
      message: "昵称必须在2-10个字符之间",
      trigger: "blur",
    },
  ],
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { validator: validCode, trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      pattern:
        /^\S*(?=\S{6,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*?.])\S*$/,
      message:
        "密码必须包含一个小写字母,一个大写字母,一个数字,一个特殊符号(!@#$%^&*?.),长度最少6位",
      trigger: "change",
    },
  ],
});

const close = () => {
  visible.value = false;
};
const openAdd = () => {
  visible.value = true;
};

const loadDeptTree = async (node, resolve) => {
  if (node && node.level === 0) {
    const data = await getDeptTree("0");
    resolve(data);
  } else {
    const data = await getDeptTree(node.data.id);
    resolve(data);
  }
};

export default defineComponent({
  setup(props, context) {
    function reloadList() {
      context.emit("reload");
    }
    function submit() {
      formRef.value.validate(valid => {
        if (valid) {
          loading.value = true;
          addUser(userForm.value)
            .then(res => {
              if (res) {
                message("保存成功", { type: "success" });
                reloadList();
                close();
              } else {
                message("保存失败", { type: "error" });
              }
            })
            .catch(e => {
              message(e.message, { type: "error" });
            })
            .finally(() => {
              loading.value = false;
            });
        }
      });
    }
    return {
      formRef,
      rules,
      loading,
      visible,
      userForm,
      close,
      submit,
      useRenderIcon,
      loadDeptTree,
    };
  },
});

export function initRoleDialog() {
  return {
    openAdd,
  };
}
</script>
<style scoped></style>
